//
//  HEUploadUtils.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/19.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEUploadUtils.h"
#import <AVFoundation/AVFoundation.h>

@interface HEUploadUtils ()

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;
@property (nonatomic, strong) NSMutableArray *tmpUrls;

@end

@implementation HEUploadUtils

- (NSMutableArray *)tmpUrls {
    if (!_tmpUrls) {
        _tmpUrls = @[].mutableCopy;
    }
    return _tmpUrls;
}

- (void)uploadVideos:(NSArray <NSURL *> *)urls progress:(WOHttpProgressBlock)progress
             success:(WOHttpRquestSuccess)success
             failure:(WOHttpRequestFailed)failure {
    
    self.tmpUrls = @[].mutableCopy;

    // 显示指示器
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD show];
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        self.group = dispatch_group_create();
        
        for (NSURL *url in urls) {
            [self changeNameurl:url block:^(NSURL * _Nonnull filePath) {
                [self.tmpUrls addObject:filePath];
            }];
        }
        
        //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
        dispatch_group_notify(self.group, queue, ^{
            [self reqProgress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
                progress(bytesProgress , totalBytesProgress);
            } success:^(id  _Nonnull responseObject) {
                success(responseObject);
            } failure:^(NSError * _Nonnull error) {
                failure(error);
            }];
        });
    });
}

- (void)changeNameurl:(NSURL *)filePathURL block:(movEncodeToMpegToolResultBlock)block {
    
    dispatch_group_enter(_group);

    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:filePathURL options:nil];
    NSString *fileName = [NSString stringWithFormat:@"output-%@.mp4", [DYTools uuid]];
    NSString * _outfilePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@", fileName];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
     
    if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {
      DLog(@"outPath = %@",_outfilePath);
      AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
      exportSession.outputURL = [NSURL fileURLWithPath:_outfilePath];
      exportSession.outputFileType = AVFileTypeMPEG4;
      [exportSession exportAsynchronouslyWithCompletionHandler:^{
        if ([exportSession status] == AVAssetExportSessionStatusCompleted) {
            DLog(@"AVAssetExportSessionStatusCompleted---转换成功");
            NSURL *tmpURL = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@",_outfilePath]];
            DLog(@"转换完成_filePath = %@\\n_filePathURL = %@", fileName, filePathURL);
            block(tmpURL);

          //获取大小和长度
//          [self SetViewText];
//          [self uploadNetWorkWithParam:@{@"contenttype":@"application/octet-stream",@"discription":description}];
        }else{
            DLog(@"转换失败,值为:%li,可能的原因:%@",(long)[exportSession status],[[exportSession error] localizedDescription]);
//          [_hud hide:YES];
//          [MyHelper showAlertWith:nil txt:@"转换失败,请重试"];
        }
          
          dispatch_group_leave(self.group);
      }];
    }
}

- (void)reqProgress:(WOHttpProgressBlock)progress
            success:(WOHttpRquestSuccess)success
            failure:(WOHttpRequestFailed)failure {
    [WOAFNetWorkingHandle uploadVideoWithBaseURL:KServerUrl suffixUrl:Kbatch parameters:@{} name:nil videoFilePaths: self.tmpUrls fileNames:nil mediaType:nil progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        progress(bytesProgress, totalBytesProgress);
    } success:^(id  _Nonnull responseObject) {
        success(responseObject);
        [self clearMovieFromDoucments];
    } failure:^(NSError * _Nonnull error) {
        failure(error);
        [self clearMovieFromDoucments];
    }];
}


- (void)clearMovieFromDoucments{
  NSFileManager *fileManager = [NSFileManager defaultManager];
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
  NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
  NSEnumerator *e = [contents objectEnumerator];
  NSString *filename;
  while ((filename = [e nextObject])) {
    DLog(@"%@",filename);
    if ([filename isEqualToString:@"tmp.PNG"]) {
        DLog(@"删除%@",filename);
      [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
      continue;
    }
    if ([[[filename pathExtension] lowercaseString] isEqualToString:@"mp4"]||
      [[[filename pathExtension] lowercaseString] isEqualToString:@"mov"]||
      [[[filename pathExtension] lowercaseString] isEqualToString:@"png"]) {
        DLog(@"删除%@",filename);
      [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
    }
  }
}

#pragma mark - photo
- (void)uploadPhotos:(NSArray <HXPhotoModel *> *)photoList progress:(WOHttpProgressBlock)progress
             success:(WOHttpRquestSuccess)success
             failure:(WOHttpRequestFailed)failure {
//    
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_async(queue, ^{
//        self.group = dispatch_group_create();
//        
//        for (HXPhotoModel *item in photoList) {
//            dispatch_group_enter(self.group);
//
//            [item getAssetURLWithSuccess:^(NSURL * _Nullable URL, HXPhotoModelMediaSubType mediaType, BOOL isNetwork, HXPhotoModel * _Nullable model) {
//                HEIMImageObject *image = [[HEIMImageObject alloc] init];
//                image.url = URL;
//                image.imageSourceType = HEIMImageSourceTypeNative;
//                [self.tmpUrls addObject: image];
//                dispatch_group_leave(self.group);
//
//            } failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
//                dispatch_group_leave(self.group);
//            }];
//        }
//        
//        //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
//        dispatch_group_notify(self.group, queue, ^{
//            [];
//        });
//    });
     
}


@end
